// pages/wechat-test/wechat-test.ts
import { authManager } from '../../api/auth-manager';
import api from '../../api/index';

interface LogItem {
  time: string;
  message: string;
  type: 'info' | 'success' | 'warning' | 'error';
}

Page({
  data: {
    isLoggedIn: false,
    userInfo: {} as any,
    logs: [] as LogItem[]
  },

  onLoad() {
    this.addLog('页面加载完成', 'info');
    this.checkLoginStatus();
  },

  onShow() {
    this.refreshUserInfo();
  },

  /** 检查登录状态 */
  checkLoginStatus() {
    const isLoggedIn = authManager.isAuthenticated();
    const currentUser = authManager.getCurrentUser();
    
    this.setData({ 
      isLoggedIn,
      userInfo: currentUser || {}
    });
    
    this.addLog(`登录状态检查: ${isLoggedIn ? '已登录' : '未登录'}`, isLoggedIn ? 'success' : 'warning');
    
    if (currentUser) {
      this.addLog(`当前用户: ${currentUser.nickname || currentUser.username || '未知'}`, 'info');
    }
  },

  /** 刷新用户信息 */
  async refreshUserInfo() {
    try {
      if (!authManager.isAuthenticated()) {
        this.addLog('未登录，无法获取用户信息', 'warning');
        return;
      }

      this.addLog('开始获取最新用户信息...', 'info');
      
      const response = await api.getUserInfo();
      
      if (response?.data?.data) {
        const userInfo = response.data.data;
        this.setData({ userInfo });
        
        this.addLog('用户信息更新成功', 'success');
        this.addLog(`用户ID: ${userInfo.id || '未获取'}`, 'info');
        this.addLog(`公众号OpenID: ${userInfo.wxOpenid || '未绑定'}`, 'info');
      } else {
        this.addLog('获取用户信息失败: 响应数据格式错误', 'error');
      }
    } catch (error: any) {
      this.addLog(`获取用户信息失败: ${error.message || error}`, 'error');
    }
  },

  /** 获取公众号授权 */
  async getOfficialAccountAuth() {
    try {
      if (!authManager.isAuthenticated()) {
        this.addLog('请先登录后再获取公众号授权', 'warning');
        return;
      }

      this.addLog('开始获取公众号授权链接...', 'info');
      
      const response = await api.post('/api/wechat/auth/get-auth-url', {});
      
      if (response?.data?.code === 0) {
        const authUrl = response.data.data;
        this.addLog('获取授权链接成功', 'success');
        this.addLog(`授权链接: ${authUrl}`, 'info');
        
        wx.showModal({
          title: '公众号授权',
          content: '需要在微信浏览器中打开授权链接完成授权。点击确定复制链接。',
          showCancel: true,
          cancelText: '取消',
          confirmText: '复制链接',
          success: (res) => {
            if (res.confirm) {
              wx.setClipboardData({
                data: authUrl,
                success: () => {
                  wx.showToast({
                    title: '链接已复制',
                    icon: 'success'
                  });
                  this.addLog('授权链接已复制到剪贴板', 'success');
                  this.addLog(' 请在微信中打开浏览器粘贴链接完成授权', 'info');
                }
              });
            }
          }
        });
      } else {
        this.addLog(`获取授权链接失败: ${response?.data?.message || '未知错误'}`, 'error');
      }
    } catch (error: any) {
      this.addLog(`获取公众号授权异常: ${error.message || error}`, 'error');
    }
  },

  /** 跳转到公众号页面 */
  goToOfficialAccount() {
    wx.showModal({
      title: '跳转公众号',
      content: '是否跳转到微信公众号页面？',
      success: (res) => {
        if (res.confirm) {
          // 这里可以配置你的公众号页面链接
          const officialAccountUrl = 'https://mp.weixin.qq.com/'; // 替换为你的公众号链接
          wx.setClipboardData({
            data: officialAccountUrl,
            success: () => {
              wx.showToast({
                title: '链接已复制',
                icon: 'success'
              });
              this.addLog('公众号链接已复制到剪贴板', 'success');
              this.addLog(' 请在微信中打开链接关注公众号', 'info');
            }
          });
        }
      }
    });
  },

  /** 发送闹钟提醒模板消息 */
  async sendAlarmReminder() {
    try {
      if (!authManager.isAuthenticated()) {
        this.addLog('请先登录后再发送消息', 'warning');
        return;
      }

      const currentUser = authManager.getCurrentUser();
      const userInfo = this.data.userInfo;
      const userId = userInfo?.id || currentUser?.id;
      
      if (!userId) {
        this.addLog('无法获取用户ID', 'error');
        return;
      }

      this.addLog('开始发送闹钟提醒模板消息...', 'info');
      
      // 使用URL参数传递userId
      const response = await api.post(`/api/wechat/template/send/alarm-reminder?userId=${userId}`, {
        deviceName: '智能水杯',
        eventType: '闹钟提醒',
        triggerTime: new Date().toLocaleString('zh-CN')
      });
      
      if (response?.data?.code === 0 && response?.data?.data === true) {
        this.addLog('闹钟提醒模板消息发送成功', 'success');
        this.addLog('✅ 如果用户已关注公众号，将收到闹钟提醒消息', 'info');
      } else {
        const message = response?.data?.message || '未知错误';
        this.addLog(`闹钟提醒模板消息发送失败: ${message}`, 'error');
        if (message.includes('40164')) {
          this.addLog(' 提示: 可能是IP白名单限制，需要在微信公众号平台配置服务器IP', 'warning');
        }
      }

    } catch (error: any) {
      this.addLog(`发送闹钟提醒异常: ${error.message || error}`, 'error');
    }
  },

  /** 发送饮水提醒模板消息 */
  async sendWaterReminder() {
    try {
      if (!authManager.isAuthenticated()) {
        this.addLog('请先登录后再发送消息', 'warning');
        return;
      }

      const currentUser = authManager.getCurrentUser();
      const userInfo = this.data.userInfo;
      const userId = userInfo?.id || currentUser?.id;
      
      if (!userId) {
        this.addLog('无法获取用户ID', 'error');
        return;
      }

      this.addLog('开始发送饮水提醒模板消息...', 'info');
      
      // 使用URL参数传递userId
      const response = await api.post(`/api/wechat/template/send/water-reminder?userId=${userId}`, {
        deviceName: '智能水杯',
        eventType: '饮水提醒',
        triggerTime: new Date().toLocaleString('zh-CN'),
        waterAmount: 800,
        goalAmount: 2000
      });
      
      if (response?.data?.code === 0 && response?.data?.data === true) {
        this.addLog('饮水提醒模板消息发送成功', 'success');
        this.addLog('✅ 如果用户已关注公众号，将收到饮水提醒消息', 'info');
      } else {
        const message = response?.data?.message || '未知错误';
        this.addLog(`饮水提醒模板消息发送失败: ${message}`, 'error');
        if (message.includes('40164')) {
          this.addLog(' 提示: 可能是IP白名单限制，需要在微信公众号平台配置服务器IP', 'warning');
        }
      }

    } catch (error: any) {
      this.addLog(`发送饮水提醒异常: ${error.message || error}`, 'error');
    }
  },

  /** 发送自定义提醒模板消息 */
  async sendCustomReminder() {
    try {
      if (!authManager.isAuthenticated()) {
        this.addLog('请先登录后再发送消息', 'warning');
        return;
      }

      const currentUser = authManager.getCurrentUser();
      const userInfo = this.data.userInfo;
      const userId = userInfo?.id || currentUser?.id;
      
      if (!userId) {
        this.addLog('无法获取用户ID', 'error');
        return;
      }

      // 显示输入对话框
      wx.showModal({
        title: '自定义提醒',
        content: '请输入提醒内容（不超过50字）',
        editable: true,
        placeholderText: '例如：该喝水啦！',
        success: async (res) => {
          if (res.confirm && res.content) {
            const reminderText = res.content.trim();
            if (reminderText.length === 0) {
              this.addLog('提醒内容不能为空', 'warning');
              return;
            }
            if (reminderText.length > 50) {
              this.addLog('提醒内容不能超过50字', 'warning');
              return;
            }

            this.addLog(`开始发送自定义提醒: ${reminderText}`, 'info');
            
            try {
              // 使用URL参数传递userId
              const response = await api.post(`/api/wechat/template/send/water-reminder?userId=${userId}`, {
                deviceName: '智能水杯',
                eventType: '爱心提醒',
                triggerTime: new Date().toLocaleString('zh-CN'),
                waterAmount: 500,
                goalAmount: 2000
              });
              
              if (response?.data?.code === 0 && response?.data?.data === true) {
                this.addLog('自定义提醒模板消息发送成功', 'success');
                this.addLog(`✅ 提醒内容: ${reminderText}`, 'info');
                this.addLog('如果用户已关注公众号，将收到自定义提醒消息', 'info');
              } else {
                const message = response?.data?.message || '未知错误';
                this.addLog(`自定义提醒模板消息发送失败: ${message}`, 'error');
                if (message.includes('40164')) {
                  this.addLog(' 提示: 可能是IP白名单限制，需要在微信公众号平台配置服务器IP', 'warning');
                }
              }
            } catch (error: any) {
              this.addLog(`发送自定义提醒异常: ${error.message || error}`, 'error');
            }
          }
        }
      });

    } catch (error: any) {
      this.addLog(`发送自定义提醒异常: ${error.message || error}`, 'error');
    }
  },

  /** 清除测试数据 */
  clearTestData() {
    wx.showModal({
      title: '确认清除',
      content: '是否清除所有测试日志？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ logs: [] });
          this.addLog('测试日志已清除', 'info');
        }
      }
    });
  },

  /** 添加日志 */
  addLog(message: string, type: LogItem['type'] = 'info') {
    const now = new Date();
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
    
    const logs = [...this.data.logs];
    logs.unshift({
      time,
      message,
      type
    });
    
    // 只保留最近50条日志
    if (logs.length > 50) {
      logs.splice(50);
    }
    
    this.setData({ logs });
    
    // 同时在控制台输出
    console.log(`[WechatTemplateTest ${time}] ${message}`);
  }
});